/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package connector;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Lattis
 */
public class ConnectorBean implements Connector{

    String name, pass, URL;
    Connection con;
    List<ConnectorEventListener> listeners = new ArrayList<ConnectorEventListener>();

    public void setName(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setPass(String pass) {
        this.pass = pass;
    }

    public String getPass() {
        return pass;
    }

    public void setURL(String URL) {
        this.URL = URL;
    }

    public String getURL() {
        return URL;
    }

    public void connect() {
        try {
            Class.forName("org.apache.derby.jdbc.ClientDriver");
            con = DriverManager.getConnection(URL, name, pass);
            fireConnected();
        } catch (Exception ex) {
            fireNotConnected();
//            Logger.getLogger(ConnectorBean.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public ResultSet execute(String sql) {
        try {
            Statement st = con.createStatement();
            ResultSet rs = st.executeQuery(sql);
            return rs;
        } catch (SQLException ex) {
            Logger.getLogger(ConnectorBean.class.getName()).log(Level.SEVERE, null, ex);
            fireErrorEvent();
        }
        return null;
    }
    public void insert(String sql){
        try{
            Statement st = con.createStatement();
            int res = st.executeUpdate(sql);
            fireOkEvent();
        }catch (SQLException e){
            fireErrorEvent();
        }
    }

    public void addConnectorEventListener(ConnectorEventListener l) {
        listeners.add(l);
    }

    public void removeConnectorEventListener(ConnectorEventListener l) {
        if(listeners.contains(l))listeners.remove(l);
    }

    private void fireNotConnected() {
        ConnectorEvent e = new ConnectorEvent(this);
        for (ConnectorEventListener l : listeners) {
            l.notConnected(e);
        }
    }

    private void fireConnected() {
        ConnectorEvent e = new ConnectorEvent(this);
        for (ConnectorEventListener l : listeners) {
            l.Connected(e);
        }
    }

    private void fireOkEvent(){
        ConnectorEvent e = new ConnectorEvent(this);
        for (ConnectorEventListener l : listeners) {
            l.OkEvent(e);
        }
    }

    private void fireErrorEvent() {
        ConnectorEvent e = new ConnectorEvent(this);
        for (ConnectorEventListener l : listeners) {
            l.ErrorEvent(e);
        }
    }
}
